package logic

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"userop_srv/global"
	"userop_srv/model"
	"userop_srv/userop_proto"
)

// 留言板列表
func (s *Server) MessageList(ctx context.Context, in *userop_proto.MessageRequest) (*userop_proto.MessageListResponse, error) {
	var messages []model.LeavingMessage
	var messageList []*userop_proto.MessageResponse

	result := global.DB.Where(&model.LeavingMessage{UserId: in.UserId}).Find(&messages)

	for _, message := range messages {
		messageList = append(messageList, &userop_proto.MessageResponse{
			Id:          message.ID,
			UserId:      message.UserId,
			MessageType: message.MessageType,
			Subject:     message.Subject,
			Message:     message.Message,
			File:        message.File,
		})
	}

	return &userop_proto.MessageListResponse{
		Total: int32(result.RowsAffected),
		Data:  messageList,
	}, nil
}

// 创建留言板
func (s *Server) CreateMessage(ctx context.Context, in *userop_proto.MessageRequest) (*userop_proto.MessageResponse, error) {
	var message model.LeavingMessage
	message.UserId = in.UserId
	message.MessageType = in.MessageType
	message.Subject = in.Subject
	message.Message = in.Message
	message.File = in.File
	tx := global.DB.Save(&message)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "创建失败")
	}
	return &userop_proto.MessageResponse{Id: message.ID}, nil
}
